#include "food.h"
#include "constants.h"
#include <algorithm>
#include <ctime>
#include <iostream>

Food::Food() : rng(std::mt19937(static_cast<unsigned int>(std::time(nullptr)))) {
    // 初始化食物位置
    position.x = rng() % WIDTH;
    position.y = rng() % HEIGHT;
}

void Food::generate(const std::vector<Snake>& snakes) {
    bool validPos;
    int attempts = 0;
    do {
        validPos = true;
        // 随机生成食物坐标（在游戏区域内）
        position.x = rng() % WIDTH;
        position.y = rng() % HEIGHT;

        // 检查食物是否落在任意蛇身上
        for (const auto& snake : snakes) {
            if (snake.checkCollision(position)) {
                validPos = false;
                attempts++;
                break;
            }
        }

        // 尝试超过10次时强制生成（避免无限循环）
        if (attempts > 10) {
            validPos = true;
            // 修复：中文输出用ASCII兼容格式，避免编码截断
            std::cout << "Jing Gao: Shi Wu Sheng Cheng Chang Shi Guo Duo, Ke Neng Chong Die!" << std::endl;
        }
    } while (!validPos);
    // 修复：中文输出用ASCII兼容格式，避免编码截断
    std::cout << "Sheng Cheng Shi Wu Wei Zhi: (" << position.x << ", " << position.y << ")" << std::endl;
}

void Food::draw(sf::RenderWindow& window) {
    sf::RectangleShape foodRect(sf::Vector2f(BLOCK_SIZE, BLOCK_SIZE));
    foodRect.setPosition(static_cast<float>(position.x * BLOCK_SIZE), static_cast<float>(position.y * BLOCK_SIZE + PANEL_HEIGHT));
    foodRect.setFillColor(FOOD_COLOR);
    foodRect.setOutlineColor(FOOD_BORDER_COLOR);
    foodRect.setOutlineThickness(2);
    window.draw(foodRect);
}

Point Food::getPosition() const {
    return position;
}